package edu.tum.cs.stageflow.benchmarkapplications.bigData;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.nio.channels.InterruptedByTimeoutException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;

import org.xml.sax.SAXException;

import com.scireum.open.xml.NodeHandler;
import com.scireum.open.xml.StructuredNode;
import com.scireum.open.xml.XMLReader;

public class LinearWikiNode {

	private static final String DIR_BENCHMARK_RESULTS = "C:/StageFlowTestDir/benchmarkresults/";
	public static long resultCounter = 0L;
	public static long counter = 0L;

	public static void main(String[] args) {
		FileInputStream fileInput = null;
		try {
			fileInput = new FileInputStream(
					"F:/Wikipedia/enwiki-latest-pages-articles.xml");
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		XMLReader reader;
		reader = new XMLReader();
		reader.addHandler("page", new NodeHandler() {

			@Override
			public void process(StructuredNode node)
					throws InterruptedException {
				try {
					counter++;
					String string = node.queryString("title");
					if (string != null && string.contains("History")) {
						resultCounter++;
					}
					if (resultCounter > 250)
						throw new InterruptedException("Done");
				} catch (XPathExpressionException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		long startTime = System.nanoTime();
		try {
			reader.parse(fileInput);
		} catch (ParserConfigurationException | SAXException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		long stopTime = System.nanoTime();
		long duration = stopTime - startTime;
		double dduration = duration;
		double totalS = duration / 60000000.0;

		try {
			PrintWriter writer = new PrintWriter(DIR_BENCHMARK_RESULTS
					+ "LinearWikiNode.csv", "UTF-8");
			writer.print("Counter;Duration;micros;ms;s;Elements/s;s/Element\n");
			String result = counter + ";" + dduration + ";" + dduration / 1000.0
					+ ";" + dduration / 1000000.0 + ";" + totalS + ";"
					+ (double) counter / totalS + ";" + totalS
					/ (double) counter + "\n";
			
			String german_result = result.replace(".", ",");
			writer.print(german_result);
			writer.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
